package com.ks.config.starter.controller.rpc;


import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;

@Controller
public class RestTemplateController {

    @Resource
    @LoadBalanced
    private RestTemplate restTemplate;

    @Value("${serviceUrl.userServicePath}")
    private String userServicePath;

    /**
     * @// FIXME: 2018/8/29 采坑点
     *  Resource/Autowired 使用细小区别
     *
     */
    @Autowired
    private EurekaClient discoveryClient;

    @RequestMapping("getServiceUrl")
    @ResponseBody
    public String serviceUrl() {
        InstanceInfo instance = discoveryClient.getNextServerFromEureka("configServer", false);
        String serviceUrl = instance.getHomePageUrl();
        return serviceUrl;
    }

    /**
     * RestTemplate 方式调用rpc方法
     * @return
     */
    @GetMapping("/restTemplateConnect/{name}")
    @ResponseBody
    public String restTemplateConnect(@PathVariable(value = "name") String name) {
        HashMap<String, String> map = new HashMap<>();
        map.put("name", name);
        String result = restTemplate.getForEntity(userServicePath + "/restTemplateConnect/{name}", String.class, map).getBody();
        System.out.println("result=" + result);
        return result;
    }

    @GetMapping("/test")
    @ResponseBody
    public String test() {
        String result = restTemplate.getForEntity(userServicePath + "/test", String.class).getBody();
        System.out.println("result=" + result);
        return result;
    }

}
